<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/4
 * Time: 15:45
 */

namespace app\lib;


class Validator
{
    public static function validate($data, $rules)
    {
        foreach ($data as $k => $v) {

            if (!isset($rules[$k])) {
                continue;
            }
            if (is_array($rules[$k])) {
                $rule = $rules[$k]['rule'];
                $error = $rules[$k]['error'];
            } else {
                $rule = $rules[$k];
            }
            $r = explode('|', $rule);
            foreach ($r as $v2) {
                $tmp = explode(':', $v2);
                switch ($tmp[0]) {
                    case 'required':
                        $res = Validator::required($data[$k]);
                        $errorMsg = $k . ' is required';
                        break;
                    case 'min':
                        $res = Validator::min($data[$k], $tmp[1]);
                        $errorMsg = $k . ' length must more chan ' . $tmp[1] . 'char';
                        break;
                    case 'max':
                        $res = Validator::max($data[$k], $tmp[1]);
                        $errorMsg = $k . ' length no more chan ' . $tmp[1] . 'char';
                }
                if (!$res) {
                    return $errorMsg;
                }
            }
        }
        return true;
    }

    public static function _validate()
    {

    }

    public static function required($value)
    {
        if (!empty($value) || $value === 0) {
            return true;
        }
        return false;
    }

    public static function min($value, $len)
    {
        if (strlen($value) >= $len) {
            return true;
        }
        return false;
    }

    public static function max($value, $len)
    {
        if (strlen($value) > $len) {
            return false;
        }
        return true;
    }
}